package com.roadjava.rbac.controller;

import com.roadjava.rbac.bean.entity.IndexRes;
import com.roadjava.rbac.bean.req.resource.AddResParam;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.bean.vo.IndexResVo;
import com.roadjava.rbac.service.IndexResService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 首页资源上传
 */
@RestController
@RequestMapping("/indexRes")
public class IndexResController {

    @Resource
    IndexResService indexResService;
    @Value("${upload.resUrl}")
    private String resUrl;

    @PostMapping("/addRes")
    public Result<String> addRes(@RequestBody AddResParam param) {
        String message = indexResService.addRes(param);
        return Result.buildSuccess(message);

    }


    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String message = indexResService.uploadFile(file);
            return Result.buildSuccess(message);
        } catch (IOException e) {
            return Result.buildFailure("上传失败");
        }
    }

    // 获取文件列表
    @GetMapping("/list")
    public Result<List<IndexResVo>> getFileList() {
        List<IndexRes> fileList = indexResService.getAllFiles();
        List<IndexResVo> res = new ArrayList<>();
        for (IndexRes indexRes : fileList) {
            IndexResVo indexResVo = new IndexResVo();
            BeanUtils.copyProperties(indexRes, indexResVo);
            indexResVo.setUrl(resUrl+"/"+indexResVo.getPath());
            res.add(indexResVo);
        }
        return Result.buildSuccess(res);
    }

    // 根据类型返回前端文件列表
    @GetMapping("/getResByType")
    public Result<List<IndexResVo>> getResByType(@RequestParam("type") Integer param) {
        List<IndexRes> fileList = indexResService.getResByType(param);
        List<IndexResVo> res = new ArrayList<>();
        for (IndexRes indexRes : fileList) {
            IndexResVo indexResVo = new IndexResVo();
            BeanUtils.copyProperties(indexRes, indexResVo);
            indexResVo.setUrl(resUrl+"/"+indexResVo.getPath());
            res.add(indexResVo);
        }
        return Result.buildSuccess(res);
    }


    // 删除文件接口
    @GetMapping("/delete/{id}")
    public Result<String> deleteFile(@PathVariable("id") Integer id) {
        try {
            String message = indexResService.deleteFile(id);
            return Result.buildSuccess(message);
        } catch (IOException e) {
            return Result.buildFailure("删除失败");
        }

    }


}
